package com.tianci.appstore.onekeySetup;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.PMUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.TaskInfo;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.widget.TipToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xfk on 2015/10/26.
 */
public class OneKeySetupReceiver extends BroadcastReceiver {
    private static String tag = "OneKeyReceiver";
    private static Context mContext = CoocaaApplication.getContext();
    private static String topicId = "";
    public enum AppStatus {
        NOT_DOWNLOADED,
        WAITING,
        DOWNLOADING,
        DOWNLOAD_PAUSED,
        DOWNLOADED,
        INSTALLING,
        UNINSTALLING,
        INSTALLED,
        HAS_NEW_VERSION
    }

    class TopicAppInfo {
        public String id;
        public String name;
        public String lmg;
        public String downloads;
        public String softwaresize;
        public String packagename;
        public String version;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals("coocaa.intent.action.OneKeySetup.Receiver")) {
            ArrayList<String> list = intent.getStringArrayListExtra("infolist");
            String id = intent.getStringExtra("topicId");

            if(id == null || id.equals("") || list == null || list.size() ==0) {
                TipToast.getInstance(mContext).showTipToast(mContext.getString(R.string.toast_onekey_setup_error));
                return;
            }

            LogUtils.i(tag, "1 id = "+id+", size = "+list.size());
            if(!topicId.equals(id) || appInfoList.size() != list.size() || appInfoList.size() == 0) {
                topicId = id;
                appInfoList.clear();
                if(list != null) {
                    for (String str: list)
                        splitString(str);
                }
            }

            onKeyDownload();
        }
    }

    private HashMap<String, DownloadTask> taskMap = new HashMap<String, DownloadTask>();
    private Map<String, String> urlMap = new HashMap<String, String>();
    private static List<TopicAppInfo> appInfoList = new ArrayList<TopicAppInfo>();

    private void splitString(String str) {
        String[] sourceStrArray = str.split("\\|");
        TopicAppInfo info = new TopicAppInfo();
         try {
             info.id = sourceStrArray[0];
             info.packagename = sourceStrArray[1];
             info.lmg = sourceStrArray[2];
             info.name = sourceStrArray[3];
             appInfoList.add(info);
         } catch (IndexOutOfBoundsException e) {
             LogUtils.i("", e.toString());
         }
    }

    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            String string = (String)msg.obj;
            TipToast.getInstance(mContext).showTipToast(string);
        }
    };

    private void onKeyDownload() {
        if(appInfoList.size() == 0) {
            return;
        }

        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                int installSize = 0;
                int unInstallSize = 0;
                List<DownloadTask> list = null;
                try {
                    list = XServiceManager.getDownloaderService()
                            .getTaskList();
                    synchronized (taskMap) {
                        taskMap.clear();
                        for (DownloadTask task : list)
                            taskMap.put(task.url, task);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                LogUtils.d(tag, "appInfoList size = "+appInfoList.size());
                for(TopicAppInfo appData: appInfoList) {
                    if(appData.packagename == null)
                        continue;
                    AppStatus status = getAppStatus(appData.packagename, "", list);
                    LogUtils.d(tag, "status = "+status);
                    if(status == AppStatus.INSTALLED) {
                        installSize++;
                        continue;
                    }

                    if(status == AppStatus.NOT_DOWNLOADED) {
                        downloadApp(appData);
                        unInstallSize++;
                    }

                    if(status == AppStatus.DOWNLOAD_PAUSED) {
                        downloadContinue(appData);
                        unInstallSize++;
                    }
                }

                if(installSize == appInfoList.size()) {
                    Message msg = new Message();
                    msg.obj = mContext.getString(R.string.toast_onekey_setup_allinstalled);
                    mHandler.sendMessage(msg);
                    return;
                }

                if(unInstallSize == 0) {
                    Message msg = new Message();
                    msg.obj = mContext.getString(R.string.toast_onekey_setup_downloading);
                    mHandler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.obj = mContext.getString(R.string.toast_start_onekey_setup);
                    mHandler.sendMessage(msg);
                }
            }
        });
    }

    private void downloadContinue(TopicAppInfo appData) {
        try {
            DownloadTask task = null;
            String download_url = getDownurl(appData.id, "");
            synchronized (taskMap) {
                task = taskMap.get(download_url);
            }
            if (task != null) {
                if (task.url == null) {
                    while (task.url == null)
                        task.url = download_url;
                }
                XServiceManager.getDownloaderService().start(task);
                DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                        DownloadExtra.class);
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void downloadApp(TopicAppInfo appData){
        if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
            return;
        String download_url = getDownurl(appData.id, "");
        LogUtils.d("download_url:" + download_url);
        if (download_url != null) {
//            String download_path = AppDataProvider.getInstance().getDownloadPath();
            try {
                DownloadTask task = taskMap.get(download_url);

                if (task == null) {
                    DownloadExtra extra = new DownloadExtra(appData.id,
                            appData.packagename, appData.lmg,
                            appData.name);
                    task = new DownloadTask(download_url);
                    task.title = appData.name;
                    task.url = download_url;
                    task.filename = appData.packagename + ".apk";
                    task.extra = extra.toString();
                    synchronized (taskMap) {
                        taskMap.put(download_url, task);
                    }
                }
                XServiceManager.getDownloaderService().add(task);
                XServiceManager.getDownloaderService().start(task);
                task = XServiceManager.getDownloaderService().refresh(task);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private String getDownurl(String appid, String usercount) {
        try {
            String downurl = null;
            synchronized (urlMap) {
                downurl = urlMap.get(appid);
            }
            if (downurl == null) {
                downurl = CoocaaApplication.getCoocaaWebService().getAppStoreService().getDownAddress(
                        Integer.valueOf(appid), usercount);
                urlMap.put(appid, downurl);
            }
            System.out.println("download url:" + downurl);
            return downurl;
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("获取应用下载地址接口",
                    Android.throwable2String(e));
            System.out.println("错误原因：" + e.getErrormsg());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private AppStatus getAppStatus(String pkg, String versionCode, List<DownloadTask> list) {

        if (pkg.equals("com.developer.fans") && Android.isPackageInstalled(mContext, pkg)) {
            return AppStatus.INSTALLED;
        }

        String status = AppStatus.NOT_DOWNLOADED.toString();
        try {
            switch (XServiceManager.getLitePMService().getAppInstallState(pkg)) {
                case PMUtils.INSTALL_STATE_INSTALLED:
                    status = AppStatus.INSTALLED.toString();
                    break;
                case PMUtils.INSTALL_STATE_INSTALLING:
                    status = AppStatus.INSTALLING.toString();
                    break;
                default:
                    break;
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        switch (AppStatus.valueOf(status)) {
            case INSTALLING:
            case UNINSTALLING:
                return AppStatus.valueOf(status);
            default:
                break;
        }

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DownloadExtra extra = DownloadExtra.parseJObject(list.get(i).extra,
                        DownloadExtra.class);
                if (extra.pkgname.equals(pkg)) {
                    // RemoteDownloaderTask task = list.get(i);
                    TaskInfo.TASK_STATE state = list.get(i).info.state;
                    LogUtils.d("status", extra.title + " TASK_STATE:" + state);
                    switch (state) {
                        case READY:
                            return AppStatus.WAITING;
                        case PROCESSING:
                            return AppStatus.DOWNLOADING;
                        case STOPED:
                            return AppStatus.DOWNLOAD_PAUSED;
                        case FINISH:
                            return AppStatus.DOWNLOADED;
                        default:
                            return AppStatus.WAITING;
                    }
                }
            }
        }
        AppInfo localInfo = null;
        try {
            localInfo = XServiceManager.getLitePMService().getAppInfo(pkg);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (localInfo != null && localInfo.versionCode > 0) {
            long newVersion = getVersionFromString(versionCode);
            long oldVersion = localInfo.versionCode;
            // long oldVersion = Tools.getVersionFromString(localInfo.versionName);
            LogUtils.d("liqiwen", "getAppStatus----newVersion---oldVersion--" + newVersion + "  "
                    + oldVersion);
            if (newVersion > oldVersion) {
                return AppStatus.HAS_NEW_VERSION;
            } else {
                return AppStatus.INSTALLED;
            }
        }
        return AppStatus.NOT_DOWNLOADED;
    }

    private long getVersionFromString(String str) {
        String subStr = "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                subStr += str.charAt(i);
            }
        }
        if (subStr.equals("")) {
            return 0;
        } else {
            return (int) Long.parseLong(subStr);
        }
    }
}
